package com.JingYan.typeHandler;


import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author DongJiaQi
 * @create 2022/9/21 16:36
 * @Description: list 与 varchar 类型互换
 * 引用方式
 *      字段上加
 *      @TableField(value = "XXX",typeHandler = ListToVarcharHandler.class)
 *      类上加
 *      @TableName(value ="XXX",autoResultMap = true)
 */
@MappedTypes(List.class)//转换出来的类型
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库用的类型
public class ListToVarcharHandler extends BaseTypeHandler<List> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List list, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(list));
    }

    @Override
    public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String listStr = rs.getString(columnName);
        return  JSON.parseArray(listStr, Object.class);
    }

    @Override
    public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String listStr = rs.getString(columnIndex);
        return  JSON.parseArray(listStr, Object.class);
    }

    @Override
    public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String listStr = cs.getString(columnIndex);
        return  JSON.parseArray(listStr, Object.class);
    }
}
